const router = require('express').Router()
const User = require('./db/userSchema.js')
const jwt = require('jsonwebtoken');
// 登录
router.get('/login', async (req, res) => {
    const data = await User.find(req.query)
    if (data.length) {
        const token = jwt.sign({
            name: req.query.name,
            password: req.query.password
        }, '123456', { expiresIn: '60s' });
        res.send({ flag: true, token, data: data[0], msg: '登录成功', code: 200 });
        return
    }
    res.send({ flag: false, msg: '密码错误', code: 300 });
})
// 注册
router.post('/addUser', async (req, res) => {
    const data = await new User({ creditScore: 100, lastRentDays: 0, status: '正常', registrationDate: new Date().getTime(), remark: '', ...req.body }).save()
    const token = jwt.sign({
        name: req.body.name,
        password: req.body.password
    }, '123456', { expiresIn: '60s' });
    res.send({ flag: true, token, code: 200, data, msg: '创建成功' });
})
// 验证 JWT 的中间件
function checkToken(req, res, next) {
    const token = req.headers['token'];
    if (token == null) return res.sendStatus(401);

    jwt.verify(token, '123456', (err, userInfo) => {
        if (err) return res.status(403).json({});
        console.log(`token在 ${(userInfo.exp - new Date().getTime() / 1000).toFixed()} 秒后过期`);
        next();
    });
}
module.exports = { jwtRouter: router, checkToken }